package cn.itcast.web.controller;


import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;;

@Controller
public class LoginController extends BaseController {


    @Reference
    private UserService userService;
    @Reference
    private ModuleService moduleService;

    @RequestMapping(path = "/login", name = "用户登录")
    public String login(String email, String password) {
        User loginUser = userService.findByEmail(email);
        if (loginUser == null) {
            request.setAttribute("error", "邮箱不存在,请重新输入");
            return "forward:/login.jsp";
        }

        String md5Hash = new Md5Hash(password, email, 2).toString();
        UsernamePasswordToken token = new UsernamePasswordToken(email,md5Hash);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
           // e.printStackTrace();
            request.setAttribute("error", "密码错误,请重新输入");
            return "forward:/login.jsp";
        }

        loginUser = (User) subject.getPrincipal();
            session.setAttribute("loginUser", loginUser);


//动态菜单查询
            List<Module> modules = moduleService.findModuleListByUser(loginUser);
            session.setAttribute("modules", modules);
            return "home/main";
        }


        //退出
        @RequestMapping(path = "/logout", name = "用户登出")
        public String logout () {
            SecurityUtils.getSubject().logout();   //登出
            session.removeAttribute("loginUser");
            return "forward:/login.jsp";
        }

        @RequestMapping(path = "/home", name = "后台管理页面")
        public String main () {
            return "home/home";
        }
    }
